#include "ArticleWidget.h"
#include "global.h"
#include <QtDebug>

int ArticleList::KeepCount = 30;

ArticleWidget::ArticleWidget(Article * article, QWidget * parent):QWidget(parent){
    qDebug() << ">> Creating a new Article Widget";
    source = article;
    setupUi(this);
    refresh();
    setAttribute(Qt::WA_DeleteOnClose);
    
}

void ArticleWidget::setSource(Article * article){
    source = article;
    refresh();
}

void ArticleWidget::refresh(Article * article){
    if (article != 0) source = article;
    author->setText(tr("%1(%2)").arg(source->author->getProperty("id"))
				.arg(source->author->getProperty("id")));
    title->setText(source->title);
    date->setText(source->time);
    content->setText(source->display());
/*    content->setText(tr("<html><body><textarea>%1\n--\n%2</textarea></body></html>")
		    .arg(source->content)
		    .arg(source->signature));*/
}

/// Defines for class ArticleList

ArticleList::ArticleList(QWidget * parent):QWidget(parent){
    index = 0;
    topic = 0;
    list.clear();
    layout = new  QVBoxLayout(this);
}

void ArticleList::reset(){
    DEBUG_F();
    for (int i = 0; i < index; i ++){
	list.at(i)->hide();
	if (i > KeepCount)
	    list.takeAt(i)->close();
    }
    index = 0;
}

void ArticleList::insertArticle ( Article * article, ArticleList::ArticleStatus /*status*/){
//     DEBUG_F();
    ArticleWidget * widget;
    if (index < list.count()){
	qDebug() << ">> Use a existed widget.";
	widget = list.at(index);
	widget -> setSource(article);
	widget -> show();
    }
    else{
	qDebug() << ">> Allocate a new widget";
	widget = new ArticleWidget(article);
// 	addScrollBarWidget(widget, Qt::AlignBottom);
	layout->addWidget(widget);
	widget->show();
	list << widget;
    }
    index ++;
}

void ArticleList::refresh(Article * /*article*/){
    for (int i = 0; i < index; i ++)
	list.at(i)->refresh();
}

void ArticleList::update(int code){
    DEBUG_F();
    if (code != 222) return;
    index = 0;
    setTopic();
    for (int i = index; i < list.count(); i ++){
	list.at(i)->hide();
    }
}

void ArticleList::setTopic(Topic * newTopic){
    DEBUG_F();
    if (topic)
	disconnect(topic, SIGNAL(newStatus(int, QString)), this, SLOT(update(int)));
    if (newTopic)
	topic = newTopic;
    topic->refreshMe();
    reset();
    qDebug() << ">> Article count:" << topic->articlePool.count();
    for (int i = 0; i < topic->articlePool.count(); i ++)
	insertArticle(topic->articlePool.at(i));
    connect(topic, SIGNAL(newStatus(int, QString)), this, SLOT(update(int)));
}

Topic * ArticleList::getTopic() const{
    return topic;
}